package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.shiro.ShiroUser;
import com.mainbo.core.util.AccountGenerator;
import com.mainbo.core.util.EncryptPassword;
import com.mainbo.modular.listener.ListenableSupport;
import com.mainbo.modular.listener.StudentListener;
import com.mainbo.modular.system.dao.PtAccountMapper;
import com.mainbo.modular.system.dao.PtStudentMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.Student;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.vo.ExportInfoVo;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.IPtResourcesService;
import com.mainbo.modular.system.service.StudentService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author xww
 * @Description //TODO
 * @Date 2020/2/26   14:11
 **/
@Service
public class StudentServiceImpl extends ServiceImpl<PtStudentMapper,Student> implements StudentService {
    @Resource
    private PtStudentMapper studentMapper;
    @Resource
    private AccountGenerator accountGenerator;
    @Resource
    private PtAccountMapper accountMapper;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private IPtResourcesService resourcesService;

    ListenableSupport listenableSupport= new ListenableSupport() {
        @Override
        public Object[] supportTypes() {
            return new Object[0];
        }
    };
    @Override
    public CommUser getOne(String name, String orgId) {
        return studentMapper.getOne(name,orgId);
    }


    @Override
    public void saveStudent(Student ptStudent) {
        //生成账号信息
        String orgId = ptStudent.getOrgId();
        PtAccount acc = new PtAccount();
        acc.setOrgId(orgId);
        acc.setUserType(SysRole.STUDENT.getId());
        String accountName = accountGenerator.validate(acc);
        String salt ="";
        String password = EncryptPassword.encryptPassword(Const.DEFAULT_PWD);
        acc.setAccount(accountName);
        acc.setPassword(password);
        acc.setSalt(salt);
        acc.setEnable(true);
        acc.setDeleted(false);

        if (ptStudent.getCellphone() != null
                && ptStudent.getCellphone().matches(PtAccount.MOBILE_PHONE_NUMBER_PATTERN)) { // 验证手机
            PtAccount model = new PtAccount();// 禁用不可恢复
            model.setDeleted(false);
            model.setEnable(true);
            model.setCellphone(ptStudent.getCellphone());
            model = accountMapper.selectOne(model);
            if (model == null) {
                acc.setCellphone(ptStudent.getCellphone());
                ptStudent.setFlag(true);
            } else {
                ptStudent.setFlag(false);
            }
        }
        ShiroUser current= ShiroKit.getUser();
        Integer count = accountMapper.insert(acc);

        // 初始化学生数据
        ptStudent.setId(acc.getId());
        assert current != null;
        ptStudent.setCrtId(current.getId());
        ptStudent.setCrtDttm(new Date());
        ptStudent.setLastupId(current.getId());
        ptStudent.setLastupDttm(new Date());
        ptStudent.setEnable(true);
        ptStudent.setGraduateState(PtClass.not_graduation);
//        if (StringUtils.isNotBlank(ptStudent.getPhoto())) {
//            resourceService.updateTmptResources(student.getPhoto());
//        }
        studentMapper.insert(ptStudent);
    }

    @Override
    public List<Student> findStudentByCondition(Student student) {
        return studentMapper.findStudentByCondition(student);
    }

    @Override
    public List<ExportInfoVo> exportStuList(UserSearchModel um) {
        Student s = new Student();

        Integer schoolYear = null;
        String orgId="";
        List<String> orgIds = new ArrayList<String>();
        List<PtOrg> orglist = new ArrayList<PtOrg>();
        if (StringUtils.isNotEmpty(um.getOrgId())) {
            orgId=um.getOrgId();
            schoolYear = MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(s.getOrgId());
        } else {
            if (um.getAreaId() != null) {
                orglist = orgService.getOrgByAreaId(um.getAreaId(), PtOrg.TP_SCHOOL);
            }
            for (PtOrg organization : orglist) {
                orgIds.add(organization.getId());
            }

            if (!CollectionUtils.isEmpty(orglist)) {
            } else {
                if (um.getAreaId() != null) {
                    orgId="-1";
                }
            }
            schoolYear = MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(um.getAreaId());
        }

        List<ExportInfoVo> stuList = studentMapper.findAll(schoolYear,orgIds,orglist,orgId);
//    for (Student student : stuList) {
//      setClassName(student);
//    }
        return stuList;
    }

    @Override
    public void updateStudent(Student student) {
        boolean flag=false;
        PtAccount account = new PtAccount();
        account.setId(student.getId());
        account.setAccount(student.getAccountName());
        student.setLastupDttm(new Date());
        if ( student.getCellphone() != null
                && student.getCellphone().matches(PtAccount.MOBILE_PHONE_NUMBER_PATTERN)) { // 验证手机
            PtAccount model = new PtAccount();// 禁用不可恢复
            model.setDeleted(false);
            model.setEnable(true);
            model.setCellphone(student.getCellphone());
            model = accountMapper.selectOne(model);
            if (model == null) {
                account.setCellphone(student.getCellphone());
                student.setFlago("1");
                flag=true;
            } else {
                if (model.getId().equals(student.getId())) {
                    student.setFlago("1");
                } else {
                    student.setFlago("0");
                }
            }
        }
        Student old = selectById(student.getId());
        // 如果变更机构
        if (old.getOrgId() != null && !old.getOrgId().equals(student.getOrgId())) {
            account.setOrgId(student.getOrgId());
            PtOrg organization = orgService.selectById(student.getOrgId());
            student.setOrgName(organization.getName());
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("oldStu", old);
            data.put("newOrgId", student.getOrgId());
            listenableSupport.fireListenableEvent(StudentListener.EVENT_UPDATE_USER_ORG, data);
           flag=true;
        }
        if (flag) {
            accountMapper.updateById(account);
        }

        if (StringUtils.isNotBlank(student.getPhoto()) && !student.getPhoto().equals(old.getPhoto())) {
            resourcesService.deleteResources(old.getPhoto());
            resourcesService.updateTmptResources(student.getPhoto());
        }
        //如果已经有校卡号
        if(StringUtils.isNotBlank(old.getStudentCardId()) && !old.getStudentCardId().equals(student.getStudentCardId())){
            student.setLastCardId(old.getStudentCardId());
            /*student.setStudentCardId(student.getStudentCardId());*/
        }
        this.updateById(student);
    }

    @Override
    public List<Student> findStudentsWithoutClass(Student student) {
        if (student.getSchoolYear() == null) {
            student.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(student.getOrgId()));
        }
        return studentMapper.findStudentList(student);
    }
}
